package com.kl.service.impl;

import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.UserScore;
import com.kl.mapper.UserScoreMapper;
import com.kl.service.IUserScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@Service
public class UserScoreServiceImpl extends ServiceImpl<UserScoreMapper, UserScore> implements IUserScoreService {

    @Autowired
    private UserScoreMapper userScoreMapper;

    @Override
    public void inserInto(Long userId,Integer score) {
        UserScore userScore = userScoreMapper.selectById(userId);
        if (userScore == null){
            userScore = new UserScore();
            userScore.setUserId(userId);
            userScore.setExpendScore(0);
            userScore.setTotalScore(0);
            userScore.setCreateTime(new Date());
            userScore.setChangeTime(new Date());
            userScoreMapper.insert(userScore);
        }
        userScore.setChangeTime(new Date());
        userScore.setTotalScore(userScore.getTotalScore() + score);
        userScoreMapper.updateById(userScore);
    }

    @Override
    public Result updateInfo(Long userId, Integer score) {
        try {
            UserScore userScore = userScoreMapper.selectById(userId);
            if (userScore.getTotalScore() > score){
                userScore.setChangeTime(new Date());
                userScore.setTotalScore(userScore.getTotalScore() - score);
                userScoreMapper.updateById(userScore);
            }else {
                return Result.build(ConstantEnum.ERROR).setResult("积分不足");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS);
    }
}
